/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package android.facebook;

import android.app.Activity;
import android.app.ContextoAndroid;
import android.app.Mensaje;
import static android.content.Context.MODE_PRIVATE;
import android.content.Intent;
import android.content.SharedPreferences;
import android.entidades.Usuario;
import android.os.Bundle;
import android.reasons.R;
import android.reasons.Wall;
import android.util.Log;
import android.web.service.WebService;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author efraingutierrez
 */
public class FacebookApp 
{
    public static final String APP_ID = "239360339588438";
    private Facebook face;
    private AsyncFacebookRunner mAsyncRunner;
    private static final String[] PERMS = new String[] { "read_stream" ,"email"};
    private SharedPreferences sharedPrefs;
    private Activity act;
    public static String TAG = "FACEAPP";
    

    public Activity getAct() {
        return act;
    }

    public Facebook getFace() {
        return face;
    }

    public void setFace(Facebook face) {
        this.face = face;
    }

    public AsyncFacebookRunner getmAsyncRunner() {
        return mAsyncRunner;
    }

    public void setmAsyncRunner(AsyncFacebookRunner mAsyncRunner) {
        this.mAsyncRunner = mAsyncRunner;
    }

    public SharedPreferences getSharedPrefs() {
        return sharedPrefs;
    }

    public void setSharedPrefs(SharedPreferences sharedPrefs) {
        this.sharedPrefs = sharedPrefs;
    }

    public void setAct(Activity act) {
        this.act = act;
    }
    
    public FacebookApp(Activity act)
    {
        this.act = act;
        face = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(face);
    }
    
    public Boolean isSesion()
    {
        initPreferences();
        return face.isSessionValid();
    }
    
    private void initPreferences()
    {
        sharedPrefs = act.getPreferences(MODE_PRIVATE);
        String access_token = sharedPrefs.getString("access_token", null);
        long expires = sharedPrefs.getLong("access_expires", 0);

        if (access_token != null) {
            face.setAccessToken(access_token);
        }

        if (expires != 0) {
            face.setAccessExpires(expires);
        }
    }

    public void requestLogIn() 
    {
        initPreferences();
        face.authorize(act, PERMS,
            new Facebook.DialogListener() {
                private boolean flagerror = false;
                @Override
                public void onCancel() {
                    // Function to handle cancel event
                    
                    Mensaje.Mostrar("CANCELADO...");
                }

                @Override
                public void onComplete(Bundle values) {
                    // Function to handle complete event
                    // Edit Preferences and update facebook acess_token
                    
                    {
                        SharedPreferences.Editor editor = sharedPrefs.edit();
                        editor.putString("access_token",face.getAccessToken());
                        editor.putLong("access_expires",face.getAccessExpires());
                        editor.commit();
                        initLocalUser();
                    }
                }

                @Override
                public void onError(DialogError error) {
                    // Function to handle error
                    
                }

                @Override
                public void onFacebookError(FacebookError fberror) {
                    // Function to handle Facebook errors
                }

            });
    }
    
     public void logoutFromFacebook() 
     {
        //initPreferences();
        mAsyncRunner.logout(ContextoAndroid.context, new AsyncFacebookRunner.RequestListener() {
            @Override
            public void onComplete(String response, Object state) {
                Log.d("Logout from Facebook", response);
                if (Boolean.parseBoolean(response) == true) {
                    // User successfully Logged out
                }
            }

            @Override
            public void onIOException(IOException e, Object state) {
            }

            @Override
            public void onFileNotFoundException(FileNotFoundException e,
                    Object state) {
            }

            @Override
            public void onMalformedURLException(MalformedURLException e,
                    Object state) {
            }

            @Override
            public void onFacebookError(FacebookError e, Object state) {
            }
        });
    }

    public void initLocalUser() 
    {
        //initPreferences();
        mAsyncRunner.request("me", new IDRequestListener());
    }
    
    private class IDRequestListener implements AsyncFacebookRunner.RequestListener {
 
                @Override
                public void onComplete(String response, Object state) {
                        
                        try {
                                JSONObject json = Util.parseJson(response);
                                final String em = json.getString("email");
                                final String idface = json.getString("id");
                                ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                                nameValuePairs.add(new BasicNameValuePair("id",em));
                                JSONArray array = WebService.getJSONArray(nameValuePairs, "Existe", "Controladores/existeUsuario.php");
                                String existe = array.getString(0);
                                //alta en la base de datos local
                                if(existe.equals("0"))
                                {
                                    ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
                                    lst.add(new BasicNameValuePair("id",em));
                                    lst.add(new BasicNameValuePair("password",""));
                                    lst.add(new BasicNameValuePair("foto",idface+".jpg"));
                                    lst.add(new BasicNameValuePair("nombre",json.getString("name")));
                                    lst.add(new BasicNameValuePair("tipo","1"));
                                    lst.add(new BasicNameValuePair("face",idface));
                                    array = WebService.getJSONArray(lst, "Alta", "Controladores/nuevoUsuario.php");
                                    String str = array.getString(0);
                                    if(str.equals("1"))
                                    {
                                        String correo = array.getString(0);
                                        String pass = array.getString(1);
                                        String nombre = array.getString(2);
                                        String foto = array.getString(3);
                                        int tipo = 1;
                                        Usuario u = new Usuario(correo,pass,nombre,foto,tipo);
                                        ContextoAndroid.usuario = u;
                                    }
                                }
                                else
                                {
                                    ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
                                    lst.add(new BasicNameValuePair("id",em));
                                    array = WebService.getJSONArray(nameValuePairs, "Usuario", "Controladores/getUsuario.php");
                                    String correo = array.getString(0);
                                    String pass = array.getString(1);
                                    String nombre = array.getString(2);
                                    String foto = array.getString(3);
                                    int tipo = 1;
                                    Usuario u = new Usuario(correo,pass,nombre,foto,tipo);
                                    ContextoAndroid.usuario = u;
                                }
                                Intent i = new Intent(act,Wall.class);
                                act.startActivity(i);
                                act.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
                                
                        } catch (JSONException e) {
                                Log.d(TAG, "JSONException: " + e.getMessage());
                        } catch (FacebookError e) {
                                Log.d(TAG, "FacebookError: " + e.getMessage());
                        }
                        catch (Exception e) {
                                
                        }
                }
 
                @Override
                public void onIOException(IOException e, Object state) {
                        Log.d(TAG, "IOException: " + e.getMessage());
                }
 
                @Override
                public void onFileNotFoundException(FileNotFoundException e,
                                Object state) {
                        Log.d(TAG, "FileNotFoundException: " + e.getMessage());
                }
 
                @Override
                public void onMalformedURLException(MalformedURLException e,
                                Object state) {
                        Log.d(TAG, "MalformedURLException: " + e.getMessage());
                }
 
                @Override
                public void onFacebookError(FacebookError e, Object state) {
                        Log.d(TAG, "FacebookError: " + e.getMessage());
                }
 
        }
}
